package com.tencent.qcloud.tim.uikit.modules.group.info;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lxj.xpopup.interfaces.OnSelectListener;
import com.manor.common.CommonAppConfig;
import com.manor.common.http.HttpCallback;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.DpUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StringUtil;
import com.tencent.imsdk.v2.V2TIMGroupMemberFullInfo;
import com.tencent.qcloud.tim.uikit.R;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.tencent.qcloud.tim.uikit.bean.ChatBgEvent;
import com.tencent.qcloud.tim.uikit.bean.GroupInfoUpdate;
import com.tencent.qcloud.tim.uikit.component.LineControllerView;
import com.tencent.qcloud.tim.uikit.component.SelectionActivity;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.component.dialog.LookGroupInfoDialog;
import com.tencent.qcloud.tim.uikit.component.dialog.ModifyNameDialog;
import com.tencent.qcloud.tim.uikit.component.dialog.TUIKitDialog;
import com.tencent.qcloud.tim.uikit.component.picture.imageEngine.impl.GlideEngine;
import com.tencent.qcloud.tim.uikit.http.TkHttpUtil;
import com.tencent.qcloud.tim.uikit.modules.group.apply.GroupApplyManagerActivity;
import com.tencent.qcloud.tim.uikit.modules.group.interfaces.IGroupMemberLayout;
import com.tencent.qcloud.tim.uikit.modules.group.member.GroupMemberInfo;
import com.tencent.qcloud.tim.uikit.modules.group.member.IGroupMemberRouter;
import com.tencent.qcloud.tim.uikit.modules.group.role.SetAdminActivity;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.qcloud.tim.uikit.utils.TUIKitLog;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;
import com.tencent.qcloud.tim.uikit.utils.UploadAvatarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;

import androidx.annotation.Nullable;

import static com.manor.common.CommonAppConfig.IMAGE_SERVER;


public class GroupInfoLayout extends LinearLayout implements IGroupMemberLayout, View.OnClickListener {

    private static final String TAG = GroupInfoLayout.class.getSimpleName();
    private TitleBarLayout mTitleBar;
    private LineControllerView mMemberView;
    private GroupInfoAdapter mMemberAdapter;
    private IGroupMemberRouter mMemberPreviewListener;
    private LineControllerView mGroupTypeView;
    private LineControllerView mGroupIDView;
    private LineControllerView mGroupNameView;
    private LineControllerView mGroupIcon;
    private LineControllerView mGroupNotice;
    private LineControllerView mNickView;
    private LineControllerView mJoinTypeView;
    private LineControllerView mTopSwitchView;
    private Button mDissolveBtn;
    private RelativeLayout rlTopNick;
    private ImageView ivGroup;
    private TextView tvGroupName;
    private TextView tvGroupIdNum;
    private LineControllerView mMuteSwitchView;
    private TextView tvNotice;
    private TextView tvGroupIntroduce;
    private TextView tvGroupAddNum;
    private LinearLayout llAdminImage;

    private GroupInfo mGroupInfo;
    private GroupInfoPresenter mPresenter;
    private ArrayList<String> mJoinTypes = new ArrayList<>();
    private ArrayList<GroupMemberInfo> adminList = new ArrayList<>();
    private boolean isLoadInfo = false;

    public GroupInfoLayout(Context context) {
        super(context);
        init();
    }

    public GroupInfoLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GroupInfoLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.group_info_layout, this);

        isLoadInfo = false;
        // 标题
        mTitleBar = findViewById(R.id.group_info_title_bar);
        mTitleBar.getRightGroup().setVisibility(GONE);
        mTitleBar.setTitle(getResources().getString(R.string.group_detail), TitleBarLayout.POSITION.MIDDLE);
        mTitleBar.setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Activity) getContext()).finish();
            }
        });
        // 成员标题
        mMemberView = findViewById(R.id.group_member_bar);
        mMemberView.setOnClickListener(this);
        mMemberView.setCanNav(true);
        // 成员列表
        GridView memberList = findViewById(R.id.group_members);
        mMemberAdapter = new GroupInfoAdapter();
        memberList.setAdapter(mMemberAdapter);
        // 群类型，只读
        mGroupTypeView = findViewById(R.id.group_type_bar);
        // 群ID，只读
        mGroupIDView = findViewById(R.id.group_account);
        // 群聊名称
        mGroupNameView = findViewById(R.id.group_name);
        mGroupNameView.setOnClickListener(this);
        mGroupNameView.setCanNav(true);
        tvGroupName = findViewById(R.id.group_tv_name);
        tvGroupIdNum = findViewById(R.id.group_id_num);

        // 群头像
        mGroupIcon = findViewById(R.id.group_icon);
        mGroupIcon.setOnClickListener(this);
        mGroupIcon.setCanNav(false);
        // 群公告
        mGroupNotice = findViewById(R.id.group_notice);
        tvNotice = findViewById(R.id.tvNotice);
        findViewById(R.id.rlNotice).setOnClickListener(this);
        mGroupNotice.setOnClickListener(this);
        mGroupNotice.setCanNav(true);
        //群介绍
        tvGroupIntroduce = findViewById(R.id.tvGroupIntroduce);
        findViewById(R.id.llGroupIntroduce).setOnClickListener(this);

        //入群申请
        findViewById(R.id.llGroupAddTube).setOnClickListener(this);
        tvGroupAddNum = findViewById(R.id.tvGroupAddNum);

        //管理员
        findViewById(R.id.group_set_admin).setOnClickListener(this);
        llAdminImage = findViewById(R.id.llAdminImage);


        // 加群方式

        mJoinTypeView = findViewById(R.id.join_type_bar);
        mJoinTypeView.setOnClickListener(this);
        mJoinTypeView.setCanNav(true);
        mJoinTypes.addAll(Arrays.asList(getResources().getStringArray(R.array.group_join_type)));
        // 群昵称
        mNickView = findViewById(R.id.self_nickname_bar);
        mNickView.setOnClickListener(this);
        mNickView.setCanNav(true);
        // 是否置顶
        mTopSwitchView = findViewById(R.id.chat_to_top_switch);
        mTopSwitchView.setCheckListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mPresenter.setTopConversation(isChecked);
            }
        });
        //禁言
        mMuteSwitchView = findViewById(R.id.chat_ban_switch);
        mMuteSwitchView.setCheckListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isLoadInfo) {
                    mPresenter.modifyGroupAllMute(isChecked);
                    mGroupInfo.setAllMute(isChecked);
                }
            }
        });
        // 退群
        mDissolveBtn = findViewById(R.id.group_dissolve_button);
        mDissolveBtn.setOnClickListener(this);

        //举报
        findViewById(R.id.group_to_report).setOnClickListener(this);

        //自定义背景
        findViewById(R.id.group_set_bg).setOnClickListener(this);

        //群头像
        ivGroup = findViewById(R.id.group_image);
        ivGroup.setOnClickListener(this);

        //
        rlTopNick = findViewById(R.id.rl_top_nick);
        rlTopNick.setOnClickListener(this);

        mPresenter = new GroupInfoPresenter(this);


    }

    @Override
    public void onClick(View v) {
        if (mGroupInfo == null) {
            TUIKitLog.e(TAG, "mGroupInfo is NULL");
            return;
        }
        if (v.getId() == R.id.group_member_bar) {
            if (mMemberPreviewListener != null) {
                mMemberPreviewListener.forwardListMember(mGroupInfo);
            }
        } else if (v.getId() == R.id.group_name || v.getId() == R.id.rl_top_nick) {
            if (isAdmin()) {
                changeGroupName();
            } else {
                // LookGroupInfoDialog.Companion.load(getContext(),"");
            }
        } else if (v.getId() == R.id.group_set_admin) {//管理员
            if (mGroupInfo.isOwner() && StringUtil.isNotEmpty(mGroupInfo.getId())) {
                SetAdminActivity.Companion.forward(getContext(), mGroupInfo.getId());
            }
        } else if (v.getId() == R.id.llGroupAddTube) {
            if (isAdmin())
                curJoin();
        } else if (v.getId() == R.id.group_icon || v.getId() == R.id.group_image) {
            if (isAdmin())
                changeGroupImg();
        } else if (v.getId() == R.id.group_notice || v.getId() == R.id.rlNotice) {

            if (isAdmin()) {
                changeNoticeText();
            } else {
                LookGroupInfoDialog.Companion.load(getContext(), "群公告", mGroupInfo.getNotice());
            }

        } else if (v.getId() == R.id.llGroupIntroduce) {//群介绍
            if (isAdmin()) {
                changeIntroduce();
            } else {
                LookGroupInfoDialog.Companion.load(getContext(), "群介绍", mGroupInfo.getIntroduction());
            }
        } else if (v.getId() == R.id.group_set_bg) {
            changeBg();
        } else if (v.getId() == R.id.group_to_report) {
            RouteUtil.forwardReport(3, mGroupInfo.getId());
        } else if (v.getId() == R.id.self_nickname_bar) {
            changeNickName();
        } else if (v.getId() == R.id.join_type_bar) {
            if (mGroupTypeView.getContent().equals("聊天室")) {
                ToastUtil.toastLongMessage("加入聊天室为自动审批，暂不支持修改");
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putString(TUIKitConstants.Selection.TITLE, getResources().getString(R.string.group_join_type));
            bundle.putStringArrayList(TUIKitConstants.Selection.LIST, mJoinTypes);
            bundle.putInt(TUIKitConstants.Selection.DEFAULT_SELECT_ITEM_INDEX, mGroupInfo.getJoinType());
            SelectionActivity.startListSelection((Activity) getContext(), bundle,
                    new SelectionActivity.OnResultReturnListener() {
                        @Override
                        public void onReturn(final Object text) {
                            mPresenter.modifyGroupInfo((Integer) text, TUIKitConstants.Group.MODIFY_GROUP_JOIN_TYPE);
                            mJoinTypeView.setContent(mJoinTypes.get((Integer) text));
                        }
                    });
        } else if (v.getId() == R.id.group_dissolve_button) {
            if (mGroupInfo.isOwner() &&
                    (!mGroupInfo.getGroupType().equals(TUIKitConstants.GroupType.TYPE_WORK)
                            || !mGroupInfo.getGroupType().equals(TUIKitConstants.GroupType.TYPE_PRIVATE))) {
                new TUIKitDialog(getContext())
                        .builder()
                        .setCancelable(true)
                        .setCancelOutside(true)
                        .setTitle("您确认解散该群?")
                        .setDialogWidth(0.75f)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.deleteGroup();
                            }
                        })
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        })
                        .show();
            } else {
                new TUIKitDialog(getContext())
                        .builder()
                        .setCancelable(true)
                        .setCancelOutside(true)
                        .setTitle("您确认退出该群？")
                        .setDialogWidth(0.75f)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.quitGroup();
                            }
                        })
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        })
                        .show();
            }
        }
    }


    private void curJoin() {
        Intent intent = new Intent(getContext(), GroupApplyManagerActivity.class);
        intent.putExtra(TUIKitConstants.Group.GROUP_INFO, mGroupInfo);
        getContext().startActivity(intent);
    }

    private void changeBg(){
        UploadAvatarUtil.instance.editAvatar((Activity) getContext(), false, new CommonCallback<String>() {
            @Override
            public void callback(String bean) {
                KLog.i("changeGroupImgBg", bean);
                if (StringUtil.isNotEmpty(bean))
                    TkHttpUtil.INSTANCE.setIMChatBg(CommonAppConfig.getInstance().getUid(), bean, new HttpCallback() {
                        @Override
                        public void onSuccess(int code, String msg, String info) {
                            if (code==0){
                                CommonAppConfig.getInstance().clearChatBg();
                                EventBus.getDefault().post(new ChatBgEvent(true));
                            }else {
                                ToastUtil.toastShortMessage(msg);
                            }
                        }
                    });
                else
                    ToastUtil.toastLongMessage("上传失败");
            }
        });
    }


    private void changeGroupImg() {
        UploadAvatarUtil.instance.editAvatar((Activity) getContext(),true, new CommonCallback<String>() {
            @Override
            public void callback(String bean) {
                KLog.e("changeGroupImg", bean);
                if (StringUtil.isNotEmpty(bean))
                    mPresenter.modifyGroupUrl(IMAGE_SERVER + bean);
                else
                    ToastUtil.toastLongMessage("上传失败");
            }
        });
    }

    private void changeIntroduce() {
        String hint = "群介绍最多35个字";
        String content = mGroupInfo.getIntroduction();
        ModifyNameDialog.Companion.load(getContext(), "修改群介绍", "请在下方输入新的群介绍", hint,content,
                35, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        mPresenter.modifyGroupIntroduce(text);
                        tvGroupIntroduce.setText(text);
                    }
                });
    }

    private void changeNoticeText() {
        String hint = "群公告最多100个字";
        String content = mGroupInfo.getNotice();
        ModifyNameDialog.Companion.load(getContext(), "修改群公告", "请在下方输入新的群公告", hint,content,
                100, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        mPresenter.modifyGroupNotice(text);
                        mGroupNotice.setContent(text);
                        tvNotice.setText(text);
                    }
                });

    }

    private void changeNickName() {
        String hint = "群昵称最多12个字";
        String content = mNickView.getContent();
        ModifyNameDialog.Companion.load(getContext(), "修改我的群昵称", "请在下方输入新的群昵称", hint,content,
                12, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        mPresenter.modifyMyGroupNickname(text);
                        mNickView.setContent(text);
                    }
                });

    }

    private void changeGroupName() {
        String hint = "群名称最多10个字";
        String content = mGroupInfo.getGroupName();
        ModifyNameDialog.Companion.load(getContext(), "修改群名称", "请在下方输入新的群名称", hint,content,
                10, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        tvGroupName.setText(text);
                        mPresenter.modifyGroupName(text.toString());
                        mGroupNameView.setContent(text.toString());
                    }
                });

    }

    private void loadGroupAdmin() {
        // llAdminImage;

        for (GroupMemberInfo memberDetail : mGroupInfo.getMemberDetails()) {
            if (memberDetail.getMemberType() == V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_ADMIN) {
                adminList.add(memberDetail);
            }
        }

        if (llAdminImage != null && llAdminImage.getVisibility() == VISIBLE){
            if (adminList.size() > 0){
                llAdminImage.removeAllViews();
                int k = Math.min(adminList.size(), 3);
                for (int i = 0; i < k; i++) {
                    ImageView img = new ImageView(getContext());
                    ViewGroup.LayoutParams params = new LayoutParams(DpUtil.dp2px(20),DpUtil.dp2px(20));
                    img.setLayoutParams(params);
                    llAdminImage.addView(img);
                    GlideEngine.loadCircleImage(img,adminList.get(i).getIconUrl());
                }

            }
        }


    }

    private boolean isAdmin() {
        return mGroupInfo.getCurRole() == V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_OWNER
                || mGroupInfo.getCurRole() == V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_ADMIN;
    }

    public void setGroupId(String groupId) {
        mPresenter.loadGroupInfo(groupId, new IUIKitCallBack() {
            @Override
            public void onSuccess(Object data) {
                setGroupInfo((GroupInfo) data);
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {

            }
        });
    }

    private void setGroupInfo(GroupInfo info) {
        if (info == null) {
            return;
        }
        this.mGroupInfo = info;
        if (mPresenter != null)
            mPresenter.loadApplyList();
        GlideEngine.loadCircleImage(ivGroup, info.getGroupUrl());
        mGroupNameView.setContent(info.getGroupName());
        tvGroupName.setText(info.getGroupName());
        tvGroupIdNum.setText("群ID：" + info.getId());

        tvGroupIntroduce.setText(info.getIntroduction());

        mGroupIDView.setContent(info.getId());
        mGroupNotice.setContent(info.getNotice());
        tvNotice.setText(info.getNotice());
        mMemberView.setContent(info.getMemberCount() + "/200");
        mMemberAdapter.setDataSource(info);
        mGroupTypeView.setContent(convertGroupText(info.getGroupType()));
        mJoinTypeView.setContent(mJoinTypes.get(info.getJoinType()));
        mNickView.setContent(mPresenter.getNickName());
        mTopSwitchView.setChecked(mGroupInfo.isTopChat());

        mDissolveBtn.setText(R.string.dissolve);


        if (mGroupInfo.isOwner()) {
            findViewById(R.id.group_set_admin).setVisibility(VISIBLE);
        } else {
            findViewById(R.id.group_set_admin).setVisibility(GONE);
        }

        if (mGroupInfo.getCurRole() == V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_OWNER
                || mGroupInfo.getCurRole() == V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_ADMIN) {
            //当前角色为群主或管理员
            mMuteSwitchView.setVisibility(VISIBLE);
            mMuteSwitchView.setChecked(mGroupInfo.isAllMute());
            findViewById(R.id.llGroupAddTube).setVisibility(VISIBLE);
            isLoadInfo = true;
        } else {
            mMuteSwitchView.setVisibility(GONE);
            findViewById(R.id.llGroupAddTube).setVisibility(GONE);
        }

        if (mGroupInfo.isOwner()) {
            //mGroupNotice.setVisibility(VISIBLE);
            mJoinTypeView.setVisibility(GONE);
            // 暂时隐藏加群方式管理
            //mJoinTypeView.setVisibility(VISIBLE);
            if (mGroupInfo.getGroupType().equals(TUIKitConstants.GroupType.TYPE_WORK)
                    || mGroupInfo.getGroupType().equals(TUIKitConstants.GroupType.TYPE_PRIVATE)) {
                mDissolveBtn.setText(R.string.exit_group);
            }
        } else {
            //mGroupNotice.setVisibility(GONE);
            mJoinTypeView.setVisibility(GONE);
            mDissolveBtn.setText(R.string.exit_group);
        }
    }

    private String convertGroupText(String groupType) {
        String groupText = "";
        if (TextUtils.isEmpty(groupType)) {
            return groupText;
        }
        if (TextUtils.equals(groupType, TUIKitConstants.GroupType.TYPE_PRIVATE)
                || TextUtils.equals(groupType, TUIKitConstants.GroupType.TYPE_WORK)) {
            groupText = "讨论组";
        } else if (TextUtils.equals(groupType, TUIKitConstants.GroupType.TYPE_PUBLIC)) {
            groupText = "公开群";
        } else if (TextUtils.equals(groupType, TUIKitConstants.GroupType.TYPE_CHAT_ROOM)
                || TextUtils.equals(groupType, TUIKitConstants.GroupType.TYPE_MEETING)) {
            groupText = "聊天室";
        }
        return groupText;
    }

    public void onGroupInfoModified(Object value, int type) {
        switch (type) {
            case TUIKitConstants.Group.MODIFY_GROUP_NAME:
                ToastUtil.toastLongMessage(getResources().getString(R.string.modify_group_name_success));
                mGroupNameView.setContent(value.toString());
                break;
            case TUIKitConstants.Group.MODIFY_GROUP_NOTICE:
                mGroupNotice.setContent(value.toString());
                mGroupInfo.setNotice(value.toString());
                ToastUtil.toastLongMessage(getResources().getString(R.string.modify_group_notice_success));
                break;
            case TUIKitConstants.Group.MODIFY_GROUP_INTRODUCE:
                tvGroupIntroduce.setText(value.toString());
                mGroupInfo.setIntroduction(value.toString());
                ToastUtil.toastLongMessage(getResources().getString(R.string.modify_group_introduce_success));
                break;
            case TUIKitConstants.Group.MODIFY_GROUP_JOIN_TYPE:
                mJoinTypeView.setContent(mJoinTypes.get((Integer) value));
                break;
            case TUIKitConstants.Group.MODIFY_MEMBER_NAME:
                ToastUtil.toastLongMessage(getResources().getString(R.string.modify_nickname_success));
                mNickView.setContent(value.toString());
                break;
            case TUIKitConstants.Group.MODIFY_GROUP_URL:
                GlideEngine.loadCircleImage(ivGroup, value.toString());
                break;
            case TUIKitConstants.Group.GROUP_APPLY_NUM:
                if (StringUtil.isNotEmpty(value.toString())) {
                    tvGroupAddNum.setVisibility(View.VISIBLE);
                    tvGroupAddNum.setText(value.toString());
                } else {
                    tvGroupAddNum.setVisibility(View.INVISIBLE);
                }
                break;
            case TUIKitConstants.Group.MODIFY_MEMBER_ALL_MUTE:
                break;
        }
    }

    public void setRouter(IGroupMemberRouter listener) {
        mMemberPreviewListener = listener;
        mMemberAdapter.setManagerCallBack(listener);
    }

    @Override
    public void setDataSource(GroupInfo dataSource) {

    }

    @Override
    public TitleBarLayout getTitleBar() {
        return mTitleBar;
    }

    @Override
    public void setParentLayout(Object parent) {

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        EventBus.getDefault().unregister(this);
        super.onDetachedFromWindow();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGroupInfoUp(GroupInfoUpdate e){
        if (mGroupInfo!=null){
            setGroupInfo(mGroupInfo);
        }
    }

}
